﻿@page "/login"

@attribute [AllowAnonymous]
@inherits PageProcessComponent
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
@inject ISnackbar Snackbar
@inject ISecureCache SecureCache
@inject IAccountService AccountService


<div class="authentication-wrapper authentication-cover">
    <MudLink Underline="Underline.None" Class="auth-cover-brand d-flex align-center gap-2">
        <span class="app-brand-logo demo">
            <MudIcon Icon="@Icons.Custom.Brands.MudBlazor" Color="Color.Primary" Size="Size.Large" />
        </span>
        <span class="app-brand-text demo fw-bold">MudBlazor</span>
    </MudLink>

    <MudGrid Class="authentication-inner m-0">
        <!-- /Left Section -->
        <MudItem lg="7" xl="8" Class="d-none d-lg-flex align-center justify-center p-5 pb-2">
            <MudImage Src="images/auth-login-illustration-light.png" Class="auth-cover-illustration w-100" Alt="auth-illustration"></MudImage>
            <MudImage Src="images/auth-cover-login-mask-light.png" Class="authentication-image" Alt="mask"></MudImage>
        </MudItem>
        <!-- /Left Section -->
        <!-- Login -->
        <MudItem lg="5" xl="4" xs="12" Class="d-flex align-center authentication-bg relative py-sm-5 px-4 py-4">
            <div class="app-layout-form pt-5 pt-lg-0">
                <h4 class="mb-2 fw-semibold">Welcome to MudBlazor! 👋</h4>
                <p class="mb-4">Please sign-in to your account and start the adventure</p>
                <MudForm Model="_loginModel" @ref="@_form" Validation="@(_loginValidator.ValidateValue)" ValidationDelay="0"
                         Class="mb-3">
                    <MudStack Spacing="3">
                        <MudTextField @bind-value="_loginModel.UserName" Label="Email or Username"
                                      For="@(() => _loginModel.UserName)"
                                      Variant="Variant.Outlined" Margin="Margin.Dense"
                                      OnlyValidateIfDirty="true">
                        </MudTextField>
                        <MudPasswordField @bind-Value="_loginModel.Password" Label="Password"
                                          For="@(() => _loginModel.Password)"
                                          Variant="Variant.Outlined" Margin="Margin.Dense"
                                          OnlyValidateIfDirty="true">
                        </MudPasswordField>
                        <MudPaper Elevation="0" class="d-flex justify-space-between">
                            <div class="app-from-check">
                                <MudCheckBox Label="Remember Me" For="(() => _loginModel.IsRemember)">
                                </MudCheckBox>
                            </div>
                            <MudLink Underline="Underline.None" Class="d-flex align-center">Forgot Password?</MudLink>
                        </MudPaper>
                        <MudButton Variant="Variant.Filled" Color="Color.Primary" FullWidth="true"
                                   OnClick="@(async () => await Submit())">
                            Sign in
                        </MudButton>
                    </MudStack>
                </MudForm>

            </div>
        </MudItem>
    </MudGrid>
</div>

@code {
    private LoginRequestDto _loginModel = new();

    private bool _passwordVisibility;
    private MudForm _form = new();
    private LoginValidator _loginValidator = new();

    protected override async Task OnInitializedAsync()
    {
        var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        if (state.User.Identity is { IsAuthenticated: true })
        {
            NavigationManager.NavigateTo("/");
        }
    }

    private async Task Submit()
    {
        await _form.Validate();

        if (_form.IsValid)
        {
            var result = await AccountService.Login(_loginModel);
            if (result != null)
            {
                if (result.Succeeded)
                {

                    await SecureCache.SetAsync("authToken", result.Data?.Token!);
                    await SecureCache.SetAsync("refreshToken", result.Data?.RefreshToken!);

                    await ((CustomAuthStateProvider)AuthenticationStateProvider).StateChangedAsync();
                }
                else
                {
                    Snackbar.Clear();
                    Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopCenter;
                    Snackbar.Add(string.Join(";", result.Messages), Severity.Error);
                }
            }
        }
    }

}